import json
import random
from django.core.paginator import Paginator
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.views import View
from django.views.decorators.http import require_http_methods
from captcha.image import ImageCaptcha

from organization.models import OrganizationModel
from student.models import StudentModel
from supervisor.models import AdminModel, JobPosting, InternshipPosting, InterviewSchedule
from django.contrib.auth.hashers import make_password, check_password


count_loging = 0

# Create supervisor views here.
class RegisterView(View):
    """ 管理员注册 """

    def get(self, request):
        """ get请求提供管理员注册界面 """
        return render(request, 'register/supervisor_register.html')

    def post(self, request):
        """ post请求实现管理员注册业务逻辑 """
        # # 对密码加密
        encrypt_pwd = make_password(request.POST.get('password'))
        # 向数据库添加一条管理员数据
        AdminModel.objects.create(admin_name=request.POST.get('admin_name'),
                                  password=encrypt_pwd,  # 开启密码加密
                                  # password=request.POST.get('password'),  # 未开启密码加密
                                  tch_num=request.POST.get('admin_num'),
                                  gender=request.POST.get('gender'),
                                  authority=request.POST.get('authority'),
                                  )

        result_data = {'code': 200}
        return JsonResponse(result_data)


# 验证职工号的唯一性
@require_http_methods(['POST'])
def check_number(request):
    """ 验证用户是否唯一 """
    result_data = {}
    # {'valid': True} 如果返回的是Ture: 表示验证合法，通过
    # {'valid': False} 如果返回的是False: 表示验证非法，不通过
    admin_num = request.POST.get('admin_num')  # 接受请求参数
    user = AdminModel.objects.filter(tch_num=admin_num)
    if user:
        # 已经存在一个职工号相同的用户
        result_data['valid'] = False
        return JsonResponse(result_data)
    else:
        # 职工号不重复就返回真
        result_data['valid'] = True
        return JsonResponse(result_data)


# 管理员登录
class LoginView(View):
    """ 管理员登录 """

    def get(self, request):
        """ get请求提供管理员登录界面 """
        return render(request, 'login/supervisor_login.html')

    def post(self, request):
        """ post请求实现管理员登录业务逻辑 """
        global count_loging
        try:
            if not request.COOKIES.get('user_locked'):  # 如果没有被封，才进行判断登录次数
                if count_loging < 4:  # 判断登录次数
                    count_loging += 1  # 每登录一次，次数加一
                    tch_num = request.POST.get('admin_num')                            # 得到职工号
                    password = request.POST.get('password')                            # 根据原始密码
                    encrypt_pwd = AdminModel.objects.get(tch_num=tch_num).password     # 根据职工号找到相应的管理，并比较密码
                    if check_password(password, encrypt_pwd):                          # 当密码正确时写入cookie
                        # 返回200状态码，前端JS会自动跳转到首页
                        result_data = {'code': 200}
                        response = JsonResponse(result_data)
                        # 登录成功在cookie中写入is_login已登录标志
                        response.set_cookie("user_status", "is_login")
                        # 并且创建一个session，将tch_num装进去
                        request.session['user_id'] = tch_num
                        return response
                    else:
                        # 当登录出错的时候返回401，表示登录出错
                        result_data = {'code': 401}
                        return JsonResponse(result_data)
                else:
                    # 登录尝试超过5次，就会设置一个cookie记录封禁的时长
                    result_data = {'code': 402}  # 402错误标识为输入次数过多
                    response = JsonResponse(result_data)
                    response.set_cookie("user_locked", "True", max_age=60*5)  # 这里max_age=封多久，60*5代表5分钟
                    count_loging = 0
                    return response
            else:
                result_data = {'code': 402}  # 402错误标识为输入次数过多
                response = JsonResponse(result_data)
                return response
        except:
            result_data = {'code': 401}
            return JsonResponse(result_data)



# 退出登录
def logout(request):
    """ 退出登录 """
    user = request.COOKIES.get('user_status')  # 查看cookie中是否有user字段
    if user:
        response = redirect('student:login')   # 当有user字段的时候我们就退出并跳转主页
        response.delete_cookie('user_status')    # 将cookie中的user字段清空
        return response
    return redirect('student:login')         # 如果没有登录的话也直接跳转主页


# 管理员的home
def home(request):
    # 管理员的level同功能页面也不同
    # 从session中取出当前用户的id，管理员的id是tch_num
    tch_num = user_id = request.session.get('user_id')

    # 通过tch_num找出这个管理员
    admin = AdminModel.objects.filter(tch_num=tch_num)[0]
    # 用户可能是学生1，企业2，管理员3，用if语句来判断
    organization = OrganizationModel.objects.filter(email=user_id)
    student = StudentModel.objects.filter(stu_num=user_id)
    if organization.exists():
        user_label = 2
        organization = organization[0]
    elif student.exists():
        user_label = 1
        student = student[0]
    else:
        user_label = 3
    # 将数据渲染到前端HTML模版里
    return render(request, 'home_page/supervisor_index.html', locals())


# 生成验证码
@require_http_methods(['GET'])
def generate_code(request):
    # 生成随机的4位数字与字母组合的验证码
    captcha_str = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 4))
    # 生成验证码图片
    image = ImageCaptcha().generate_image(captcha_str)
    # 将验证码存入session，方便后续验证
    request.session['verify_code'] = captcha_str
    # 将验证码图片以PNG格式返回给前端
    response = HttpResponse(content_type='image/png')
    image.save(response, 'PNG')
    return response


# 校验验证码
@require_http_methods(['POST'])
def verify_code(request):
    """验证: 验证码是否正确"""
    # {'valid': True} 如果返回的是Ture: 表示验证合法，通过
    # {'valid': False} 如果返回的是False: 表示验证非法，不通过
    result_data = {'valid': True}  # 先定义一个默认的返回参数
    code1 = request.POST.get('captcha')  # 接受请求参数
    # 服务器里面在前一次请求的时候就已经存了验证码
    code2 = request.session['verify_code']
    if not code1.lower() == code2.lower():
        # 客户端的验证码写错了
        result_data['valid'] = False
    return JsonResponse(result_data)



class ManageStudent(View):
    """ 可以增删改查用户 """
    def get(self, request):
        # 当前登录用户的名字

        tch_num = user_id = request.session.get('user_id')
        admin = AdminModel.objects.filter(tch_num=tch_num)[0]
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
        # 获取所有学生、教职工、组织、管理员
        student_all = StudentModel.objects.all()

        # 实例化分页器
        p = Paginator(student_all, 5)  # 默认显示学生，一页6个学生

        # 获取第几页的数据
        page_number = request.GET.get('page')
        # 返回页面对象
        page_obj = p.get_page(page_number)

        return render(request, 'supervisor/manage-student.html', locals())


    def post(self, request):
        """删除用户"""
        # 获得我要删除的用户ID
        user_id = request.POST.get('stu_id')
        # 根据ID找到具体的用户信息，然后删除
        # StudentModel.objects.filter(id=user_id).delete()
        print(user_id)

        return redirect('supervisor:manage_student')



class ManageOrganization(View):
    def get(self, request):
        # 当前登录用户的名字
        tch_num = user_id = request.session.get('user_id')
        admin = AdminModel.objects.filter(tch_num=tch_num)
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
            admin = admin[0]
        organization_all = OrganizationModel.objects.all()

        # 实例化分页器
        p = Paginator(organization_all, 5)  # 默认显示学生，一页6个学生

        # 获取第几页的数据
        page_number = request.GET.get('page')
        # 返回页面对象
        page_obj = p.get_page(page_number)

        return render(request, 'supervisor/manage-organization.html', locals())

    def post(self, request):
        """删除用户"""
        # 获得我要删除的用户ID
        user_id = request.POST.get('org_id')
        # 根据ID找到具体的用户信息，然后删除
        # OrganizationModel.objects.filter(id=user_id).delete()
        print(user_id)

        return redirect('supervisor:manage_organization')


class ManageJob(View):
    def get(self, request):
        # 当前登录用户的名字
        tch_num = user_id = request.session.get('user_id')
        admin = AdminModel.objects.filter(tch_num=tch_num)
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
            admin = admin[0]
        job_all = JobPosting.objects.all()

        # 实例化分页器
        p = Paginator(job_all, 5)  # 默认显示学生，一页6个学生

        # 获取第几页的数据
        page_number = request.GET.get('page')
        # 返回页面对象
        page_obj = p.get_page(page_number)

        return render(request, 'supervisor/manage-job.html', locals())

    def post(self, request):
        """删除用户"""
        # 获得我要删除的用户ID
        user_id = request.POST.get('job_id')
        # 根据ID找到具体的用户信息，然后删除
        # JobPosting.objects.filter(id=user_id).delete()
        print(user_id)

        return redirect('supervisor:manage_job')


class ManageInterview(View):
    def get(self, request):
        # 当前登录用户的名字
        tch_num = user_id = request.session.get('user_id')
        admin = AdminModel.objects.filter(tch_num=tch_num)
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
            admin = admin[0]
        job_all = InterviewSchedule.objects.all()

        # 实例化分页器
        p = Paginator(job_all, 5)  # 默认显示学生，一页6个学生

        # 获取第几页的数据
        page_number = request.GET.get('page')
        # 返回页面对象
        page_obj = p.get_page(page_number)

        return render(request, 'supervisor/manage-interview.html', locals())

    def post(self, request):
        """删除用户"""
        # 获得我要删除的用户ID
        user_id = request.POST.get('id')
        # 根据ID找到具体的用户信息，然后删除
        # InterviewSchedule.objects.filter(id=user_id).delete()
        print(user_id)

        return redirect('supervisor:manage_interview')

class ManageInternship(View):
    def get(self, request):
        # 当前登录用户的名字
        tch_num = user_id = request.session.get('user_id')
        admin = AdminModel.objects.filter(tch_num=tch_num)
        # 用户可能是学生1，企业2，管理员3，用if语句来判断
        organization = OrganizationModel.objects.filter(email=user_id)
        student = StudentModel.objects.filter(stu_num=user_id)
        if organization.exists():
            user_label = 2
            organization = organization[0]
        elif student.exists():
            user_label = 1
            student = student[0]
        else:
            user_label = 3
            admin = admin[0]
        internship_all = InternshipPosting.objects.all()

        # 实例化分页器
        p = Paginator(internship_all, 5)  # 默认显示学生，一页6个学生

        # 获取第几页的数据
        page_number = request.GET.get('page')
        # 返回页面对象
        page_obj = p.get_page(page_number)

        return render(request, 'supervisor/manage-internship.html', locals())

    def post(self, request):
        """删除用户"""
        # 获得我要删除的用户ID
        user_id = request.POST.get('id')
        # 根据ID找到具体的用户信息，然后删除
        # InternshipPosting.objects.filter(id=user_id).delete()
        print(user_id)

        return redirect('supervisor:manage_internship')
